package com.naiterui.ehp.bs.esign.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;

import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bs.esign.exception.ExceptionCodes;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description 签名工具类
 * @Author gongbaoqiang
 * @Date 2019/12/23 4:39 PM
 */
@Slf4j
public class SignUtils {

    /**
     * 将文件生成base64字符串
     */
    public static String encodeBase64File(String path) throws BusinessException {
        return cn.hutool.core.codec.Base64.encode(new File(path));
    }

    /**
     * <p>将base64字符解码保存文件</p>
     *
     * @param base64Code
     * @param targetPath
     *
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code, String targetPath) throws BusinessException {

        byte[] buffer = Base64.decodeBase64(base64Code);
        File file = new File(targetPath);
        FileOutputStream out = null;
        try {
            FileUtils.forceMkdirParent(file);
            out = new FileOutputStream(targetPath);
            out.write(buffer);
        } catch (IOException e) {
            throw new BusinessException(ExceptionCodes.BASE64_DECODE_ERROR);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    throw new BusinessException(ExceptionCodes.BASE64_DECODE_ERROR);
                }
            }
        }

    }
}
